﻿using System.Net.NetworkInformation;
using System.Net;

namespace Common.Tools
{
    /// <summary>
    /// 应用配置
    /// </summary>
    public class AppAddress
    {
        #region 字段

        /// <summary>
        /// 实例
        /// </summary>
        private static AppAddress _instance;
        /// <summary>
        /// 静态实例
        /// </summary>
        public static AppAddress Instance
        {
            get
            {
                return _instance;
            }
        }
        #endregion
        /// <summary>
        /// 静态实例
        /// </summary>
        public static void SetInstance(int port)
        {
            if (_instance == null)
            {
                _instance = GetConfig(port);
            }
        }
        /// <summary>
        /// Ip地址
        /// </summary>
        public string Ip { get; set; }
        /// <summary>
        /// 端口
        /// </summary>
        public int Port { get; set; }
        /// <summary>
        /// 设置端口
        /// </summary>
        /// <param name="port"></param>
        public void SetPort(int port)
        {
            Port = port;
        }


        #region 加载配置

        /// <summary>
        /// 加载配置
        /// </summary>
        private static AppAddress GetConfig(int port)
        {
            try
            {
                var config = new AppAddress()
                {
                    Ip = GetLocalIPAddress(),
                    Port = port
                };
                return config;
            }
            catch (Exception ex)
            {
                return new AppAddress();
            }
        }
        /// <summary>
        /// 获取本地Ip
        /// </summary>
        /// <returns></returns>
        private static string GetLocalIPAddress()
        {
            var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces()
                .Where(n => n.OperationalStatus == OperationalStatus.Up && n.NetworkInterfaceType != NetworkInterfaceType.Loopback)
                .ToList();

            foreach (var networkInterface in networkInterfaces)
            {
                var ipProperties = networkInterface.GetIPProperties();
                var ipAddress = ipProperties.UnicastAddresses.FirstOrDefault(addr => addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)?.Address;

                if (ipAddress != null)
                {
                    return ipAddress.ToString();
                }
            }

            return IPAddress.None.ToString(); // or throw exception if desired
        }
        #endregion
    }
}
